package ar.com.notarip.bb.infosubte;

import java.util.Hashtable;
import net.rim.device.api.command.Command;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.Background;
import net.rim.device.api.ui.decor.BackgroundFactory;
import net.rim.device.api.ui.decor.Border;
import net.rim.device.api.ui.decor.BorderFactory;
import net.rim.device.api.util.StringProvider;
import ar.com.notarip.bb.infosubte.util.Util;

/**
 *
 *  @author pablo notari (notarip@gmail.com)
 */
public final class InfoScreen extends MainScreen {

	
	private HorizontalFieldManager _horizontalManager;
	private VerticalFieldManager _verticalManager;
	private MenuItem _refresh = new MenuItem(new StringProvider("Actualizar"), 1, 2);
    private MenuItem _copyToClipboard = new MenuItem(new StringProvider("Copiar Estados"), 3, 3);
    private MenuItem _options = new MenuItem(new StringProvider("Opciones"), 2, 1);
    private Opciones _opcionesCmd;
    
    private Hashtable _fields = new Hashtable();
    
    private int _top, _down;
    
    private static final int AJUSTAR_IMAGEN = 1;
    private static final int AJUSTAR_FIELD = 2;
    private static final int NO_AJUSTAR = 3;
    String titulo = "InfoSubte";
    RichTextField _title;
    boolean firstDone;
    
    
    /**
     * Creates a new MyScreen object
     */
    public InfoScreen() {
    	    	
        setBackground(BackgroundFactory.createSolidBackground(Color.BLACK));
        
    	/*titulo*/
    	_title = new RichTextField(titulo);
        setTitle(_title);
        
    	
    	
    	_horizontalManager = new HorizontalFieldManager( Manager.USE_ALL_WIDTH | Manager.USE_ALL_HEIGHT |
    			Manager.HORIZONTAL_SCROLL | Manager.VERTICAL_SCROLL);
    	
    	 _verticalManager = new VerticalFieldManager(Manager.USE_ALL_WIDTH | Manager.USE_ALL_HEIGHT 
    			){
    		 
    		 protected void paintBackground(Graphics graphics) {
    			 
    			 graphics.setBackgroundColor(Color.BLACK);
                 graphics.clear();
    			 super.paintBackground(graphics);
    			
    		}
    		 
    	 };
    	 
    	 _horizontalManager.add(_verticalManager);
    	
    	/*contenedor de los fields*/
    	add(_horizontalManager);
        
        /*se inicializan los fields*/
        init();
        
    }
    

    public boolean onClose() {
    	
    	if (OpcionesService.getPushTimeAsInt() > 0){
    		UiApplication.getUiApplication().requestBackground();
    		return true;
    	}
    	
    	return super.onClose();
    }
    
    /*
     * se dispara cuando se vuelve de las opciones, en 
     * general cuando el screen vuelve al top
     * 
     * */
    protected void onExposed() {

    	super.onExposed();
    	
    	/*Que no actualice si se selecciono algo del menu*/
    	
    	if (_opcionesCmd != null && _opcionesCmd.wasSelected()){
    		_opcionesCmd.setSelected(false);
    		init();
    	}

    }

    
    public void init() {
    	
    	String initMsg = Util.DEFAULT_STATUS;
    	firstDone = false;
    	
    	_fields.clear();
    	
    	for (int i = 0; i < Util.lines.length; i++) {
			
    		buildField(Util.lines[i], initMsg);
    		
		}
    	
    	loadFields();
    	
	    /*se lanza el hilo de la consulta*/
        Thread t = new Thread(new ConnectThread());
        t.start();
				

    }
    
    private class ConnectThread implements Runnable {

        public void run() {
        	
        	Respuesta respuesta;
        	ConsultaService consulta;
        	firstDone = false;

        	
        	while (OpcionesService.getPushTimeAsInt() > 0 || !firstDone){
        		
        		int pushTime = OpcionesService.getPushTimeAsInt();
        		
        	
	    		consulta = new ConsultaService();
	    	
	        	respuesta = consulta.consultarSubte(Util.DEFAULT_STATUS);
	        	
	        	if (respuesta.wasSucces()){
	        		
		        	for (int i = 0; i < Util.lines.length; i++) {
		        		String line = Util.lines[i];
		        		String estado = Util.normalizeString((String)respuesta.getEstados().get(line)); 
		        		RichTextField field = (RichTextField) ((HorizontalFieldManager)_fields.get(line)).getField(1);
		        		field.setText(" " + estado);
					}
		        	
		        	firstDone = true;
		        
		        	_title.setText(titulo + " - Actualizado a las " + Util.getHour() );
	        	}
		        int sleep;
		        if (pushTime > 0){
		        	sleep = pushTime*1000*60;
		        	try {
						Thread.sleep(sleep);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		        }
	
	        }
        }
    }
        
    
private void buildField(String line, String initMsg) {
		
		RichTextField field = new RichTextField();
		HorizontalFieldManager hm = new HorizontalFieldManager(Manager.HORIZONTAL_SCROLL);
		int color = 0x656565;
		
		hm.setPadding(5, 0, 0, 0);
		
	    
		/* Se guardan en un mapa */
		_fields.put(line, hm);
		
		XYEdges thickPadding = new XYEdges(0, 0, 0, 0);

	    Border roundedBorder = BorderFactory.createSimpleBorder(thickPadding, Border.STYLE_SOLID);
	    Background solidBackground = BackgroundFactory.createSolidBackground(color);

		
	    /*Estilo de los fileds*/
	    field.setFont(Font.getDefault().derive(Font.BOLD));
	    field.setText(initMsg);
        field.setBorder(roundedBorder);
        field.setBackground(solidBackground);
        
        /*Se hacen los resize la de las imagenes */
        int height = 30;
        int width = 30;
        BitmapField image =  new BitmapField(Util.getBitmapResized(Util.getImgLinea(line), height, width));
        image.setBackground(BackgroundFactory.createSolidBackground(color));
        

        hm.add(image);
        
        
        int alturaHm = hm.getPreferredHeight();
        int alturaField = field.getPreferredHeight();

        
        int ajustar = ajustar(alturaHm, alturaField);
        
        if (ajustar == AJUSTAR_IMAGEN){
        	
            image.setPadding(_top, 0, _down, 0);
        	
        }else if (ajustar == AJUSTAR_FIELD) {
        	
        	field.setPadding(_top, 0, _down, 0);
        	
        }
        
        hm.add(field);



	}

private int ajustar(int alturaHm, int alturaField) {
	
	int ajustar = NO_AJUSTAR;
	int dif = 0;
	int top = 0;
	int down = 0;
	if (alturaHm > alturaField){
		
		dif = alturaHm - alturaField;
        
        ajustar =  AJUSTAR_FIELD;
        
	}else if (alturaHm < alturaField){
		
		dif = alturaField - alturaHm;
        
        ajustar = AJUSTAR_IMAGEN;
		
	}
	
    top = dif/2;
    down = dif/2;
    
  
    if (Util.esImpar(dif))
    	down += 1;
    
    
    _top = top>0 ? top : 0;
    _down = down>0 ? down: 0;

    
    return ajustar;
}

private void loadFields() {
	
	removeFields();
	
	for (int i = 0; i < Util.lines.length; i++) {
		
		if (OpcionesService.validateOptions(Util.getLetraLinea(i))){
			
			_verticalManager.add(((HorizontalFieldManager) _fields.get(Util.lines[i])));
			
		}
		
	}
	
}

private void removeFields() {
	
	_verticalManager.deleteAll();
	
}



    public void makeMenu(Menu menu, int instance) {
    	
    	super.makeMenu(menu, instance);
    	
    	
    	/* Opcion de actualizar al menu*/
    	_refresh.setCommandContext(this);
    	_refresh.setCommand(new Command(new Actualizar(this)));
    	menu.add(_refresh);
    	
    	/*Opcion de copiar todos los estados a la papelera*/
    	
    	_copyToClipboard.setCommandContext(this);
    	_copyToClipboard.setCommand(new Command(new Copiar(_verticalManager)));
    	menu.add(_copyToClipboard);
    	
    	/*Opcion para el screen de opciones*/
    	_options.setCommandContext(this);
    	_opcionesCmd = new Opciones();
    	_options.setCommand(new Command(_opcionesCmd));
    	menu.add(_options);
    	

    	
    }
        
}